<template>
  <div class="min-h-screen flex items-center justify-center relative overflow-hidden py-12 px-4 sm:px-6 lg:px-8">
    <!-- 背景装饰 -->
    <div class="absolute inset-0 bg-gradient-to-br from-primary-50 via-purple-50 to-pink-50 dark:from-gray-900 dark:via-purple-900/20 dark:to-pink-900/20">
      <div class="absolute top-0 -left-4 w-72 h-72 bg-purple-300 dark:bg-purple-600 rounded-full mix-blend-multiply dark:mix-blend-overlay filter blur-xl opacity-30 animate-blob"></div>
      <div class="absolute top-0 -right-4 w-72 h-72 bg-pink-300 dark:bg-pink-600 rounded-full mix-blend-multiply dark:mix-blend-overlay filter blur-xl opacity-30 animate-blob animation-delay-2000"></div>
      <div class="absolute -bottom-8 left-20 w-72 h-72 bg-primary-300 dark:bg-primary-600 rounded-full mix-blend-multiply dark:mix-blend-overlay filter blur-xl opacity-30 animate-blob animation-delay-4000"></div>
    </div>

    <!-- 主内容 -->
    <div class="max-w-md w-full relative z-10">
      <!-- Logo 和标题 -->
      <div class="text-center mb-8">
        <div class="flex justify-center mb-4">
          <div class="p-3 rounded-2xl bg-gradient-to-br from-primary-600 to-purple-600 shadow-lg">
            <Icon name="heroicons:code-bracket" class="w-8 h-8 text-white" />
          </div>
        </div>
        <h2 class="text-3xl font-bold gradient-text mb-2">
          欢迎来到开发者导航
        </h2>
        <p class="text-gray-600 dark:text-gray-400">
          开发者的专属工具导航平台
        </p>
      </div>

      <!-- 登录卡片 -->
      <div class="card p-8 shadow-2xl backdrop-blur-sm bg-white/80 dark:bg-gray-800/80">
        <!-- 切换按钮 -->
        <div class="flex space-x-2 mb-6 p-1 bg-gray-100 dark:bg-gray-700 rounded-lg">
          <button
            v-for="tab in tabs"
            :key="tab.key"
            @click="activeTab = tab.key"
            :class="[
              'flex-1 py-2 px-4 rounded-md text-sm font-medium transition-all',
              activeTab === tab.key
                ? 'bg-white dark:bg-gray-800 text-primary-600 dark:text-primary-400 shadow-sm'
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
            ]"
          >
            {{ tab.label }}
          </button>
        </div>

        <!-- 密码登录 -->
        <form v-if="activeTab === 'password'" @submit.prevent="handlePasswordLogin" class="space-y-5">
          <!-- 邮箱输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              邮箱地址
            </label>
            <div class="relative">
              <Icon name="heroicons:envelope" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="passwordForm.email"
                type="email"
                required
                class="input pl-10"
                placeholder="请输入邮箱"
              />
            </div>
          </div>

          <!-- 密码输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              密码
            </label>
            <div class="relative">
              <Icon name="heroicons:lock-closed" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="passwordForm.password"
                :type="showPassword ? 'text' : 'password'"
                required
                class="input pl-10 pr-10"
                placeholder="请输入密码"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
              >
                <Icon :name="showPassword ? 'heroicons:eye-slash' : 'heroicons:eye'" class="w-5 h-5" />
              </button>
            </div>
          </div>

          <!-- 图形验证码 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              验证码
            </label>
            <div class="flex space-x-2">
              <input
                v-model="passwordForm.captcha"
                type="text"
                required
                class="input flex-1"
                placeholder="请输入验证码"
                maxlength="4"
              />
              <div
                v-html="captchaSvg"
                @click="refreshCaptcha"
                class="cursor-pointer bg-gray-100 dark:bg-gray-700 rounded-lg p-2 hover:opacity-80 transition-opacity"
                style="width: 120px; height: 40px;"
              />
            </div>
          </div>

          <!-- 记住我和忘记密码 -->
          <div class="flex items-center justify-between text-sm">
            <label class="flex items-center">
              <input type="checkbox" v-model="rememberMe" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500 mr-2" />
              <span class="text-gray-600 dark:text-gray-400">记住我</span>
            </label>
            <button type="button" class="text-primary-600 hover:text-primary-700 dark:text-primary-400">
              忘记密码？
            </button>
          </div>

          <!-- 登录按钮 -->
          <button
            type="submit"
            :disabled="isLoading"
            class="btn btn-primary w-full"
          >
            <Icon v-if="isLoading" name="svg-spinners:180-ring" class="w-5 h-5" />
            <span>{{ isLoading ? '登录中...' : '登录' }}</span>
          </button>
        </form>

        <!-- 邮箱验证码登录 -->
        <form v-else-if="activeTab === 'email'" @submit.prevent="handleEmailLogin" class="space-y-5">
          <!-- 邮箱输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              邮箱地址
            </label>
            <div class="relative">
              <Icon name="heroicons:envelope" class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                v-model="emailForm.email"
                type="email"
                required
                class="input pl-10"
                placeholder="请输入邮箱"
              />
            </div>
          </div>

          <!-- 验证码输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              邮箱验证码
            </label>
            <div class="flex space-x-2">
              <input
                v-model="emailForm.code"
                type="text"
                required
                class="input flex-1"
                placeholder="请输入6位验证码"
                maxlength="6"
              />
              <button
                type="button"
                @click="sendEmailCode"
                :disabled="countdown > 0 || isSending"
                class="btn btn-secondary whitespace-nowrap"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
              </button>
            </div>
          </div>

          <!-- 登录按钮 -->
          <button
            type="submit"
            :disabled="isLoading"
            class="btn btn-primary w-full"
          >
            <Icon v-if="isLoading" name="svg-spinners:180-ring" class="w-5 h-5" />
            <span>{{ isLoading ? '登录中...' : '登录 / 注册' }}</span>
          </button>

          <p class="text-xs text-center text-gray-500 dark:text-gray-400">
            未注册的邮箱将自动创建账号
          </p>
        </form>

        <!-- 分隔线 -->
        <div class="relative my-6">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-gray-300 dark:border-gray-600"></div>
          </div>
          <div class="relative flex justify-center text-sm">
            <span class="px-4 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">
              其他登录方式
            </span>
          </div>
        </div>

        <!-- 第三方登录（占位） -->
        <div class="grid grid-cols-3 gap-3">
          <button
            type="button"
            disabled
            class="flex items-center justify-center py-3 px-4 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors opacity-50 cursor-not-allowed"
            title="即将推出"
          >
            <Icon name="simple-icons:wechat" class="w-5 h-5 text-green-600" />
          </button>
          <button
            type="button"
            disabled
            class="flex items-center justify-center py-3 px-4 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors opacity-50 cursor-not-allowed"
            title="即将推出"
          >
            <Icon name="simple-icons:github" class="w-5 h-5" />
          </button>
          <button
            type="button"
            disabled
            class="flex items-center justify-center py-3 px-4 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors opacity-50 cursor-not-allowed"
            title="即将推出"
          >
            <Icon name="heroicons:phone" class="w-5 h-5 text-blue-600" />
          </button>
        </div>

        <!-- 底部提示 -->
        <p class="mt-6 text-center text-sm text-gray-600 dark:text-gray-400">
          登录即表示同意
          <NuxtLink to="/terms" class="text-primary-600 hover:text-primary-700 dark:text-primary-400">
            服务条款
          </NuxtLink>
          和
          <NuxtLink to="/privacy" class="text-primary-600 hover:text-primary-700 dark:text-primary-400">
            隐私政策
          </NuxtLink>
        </p>
      </div>

      <!-- 注册提示 -->
      <p class="mt-6 text-center text-sm text-gray-600 dark:text-gray-400">
        还没有账号？
        <NuxtLink to="/register" class="text-primary-600 hover:text-primary-700 dark:text-primary-400 font-medium">
          立即注册
        </NuxtLink>
      </p>
    </div>
  </div>
</template>

<script setup lang="ts">
// 已登录用户不能访问登录页
definePageMeta({
  middleware: ['guest'],
})

const authStore = useAuthStore()
const route = useRoute()
const { $api } = useNuxtApp()
const toast = useToast()

// 标签页
const tabs = [
  { key: 'password', label: '密码登录' },
  { key: 'email', label: '邮箱登录' },
]
const activeTab = ref('password')

// 密码登录表单
const passwordForm = ref({
  email: '',
  password: '',
  captcha: '',
})
const showPassword = ref(false)
const rememberMe = ref(false)

// 邮箱验证码登录表单
const emailForm = ref({
  email: '',
  code: '',
})

// 图形验证码
const captchaSvg = ref('')
const captchaId = ref('')

// 倒计时
const countdown = ref(0)
const isSending = ref(false)

// 加载状态
const isLoading = ref(false)

/**
 * 获取图形验证码
 */
const refreshCaptcha = async () => {
  try {
    const response: any = await $api('/auth/captcha')
    captchaSvg.value = response.captchaSvg
    captchaId.value = response.captchaId
  } catch (error) {
    console.error('获取验证码失败', error)
  }
}

/**
 * 发送邮箱验证码
 */
const sendEmailCode = async () => {
  if (!emailForm.value.email) {
    return toast.warning('请输入邮箱地址')
  }

  try {
    isSending.value = true
    await $api('/auth/email-code/send', {
      method: 'POST',
      body: { email: emailForm.value.email },
    })
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

    toast.success('验证码已发送，请查收邮件')
  } catch (error: any) {
    toast.error(error.data?.message || '发送失败，请稍后重试')
  } finally {
    isSending.value = false
  }
}

/**
 * 密码登录
 */
const handlePasswordLogin = async () => {
  try {
    isLoading.value = true

    // 验证图形验证码
    const verifyResult: any = await $api('/auth/captcha/verify', {
      method: 'POST',
      body: {
        captchaId: captchaId.value,
        code: passwordForm.value.captcha,
      },
    })

    if (!verifyResult.valid) {
      toast.error(verifyResult.message || '验证码错误')
      refreshCaptcha()
      passwordForm.value.captcha = ''
      return
    }

    // 登录
    const response: any = await $api('/auth/login', {
      method: 'POST',
      body: {
        email: passwordForm.value.email,
        password: passwordForm.value.password,
      },
    })

    // 保存登录状态
    authStore.setToken(response.token)
    authStore.setUser(response.user)

    // 显示成功提示
    toast.success('登录成功！')

    // 跳转
    const redirect = route.query.redirect as string || '/'
    setTimeout(() => navigateTo(redirect), 500)
  } catch (error: any) {
    toast.error(error.data?.message || '登录失败，请检查邮箱和密码')
    refreshCaptcha()
    passwordForm.value.captcha = ''
  } finally {
    isLoading.value = false
  }
}

/**
 * 邮箱验证码登录
 */
const handleEmailLogin = async () => {
  try {
    isLoading.value = true

    const response: any = await $api('/auth/email-code/login', {
      method: 'POST',
      body: {
        email: emailForm.value.email,
        code: emailForm.value.code,
      },
    })

    // 保存登录状态
    authStore.setToken(response.token)
    authStore.setUser(response.user)

    // 显示成功提示
    toast.success('登录成功！')

    // 跳转
    const redirect = route.query.redirect as string || '/'
    setTimeout(() => navigateTo(redirect), 500)
  } catch (error: any) {
    toast.error(error.data?.message || '登录失败，请检查验证码')
  } finally {
    isLoading.value = false
  }
}

// 页面加载时获取验证码
onMounted(() => {
  refreshCaptcha()
})

// SEO
useHead({
  title: '登录 - DevToolsHub',
  meta: [
    { name: 'description', content: '登录 DevToolsHub，访问您的个人工具库。' },
  ],
})
</script>

<style scoped>
@keyframes blob {
  0%, 100% {
    transform: translate(0, 0) scale(1);
  }
  33% {
    transform: translate(30px, -50px) scale(1.1);
  }
  66% {
    transform: translate(-20px, 20px) scale(0.9);
  }
}

.animate-blob {
  animation: blob 7s infinite;
}

.animation-delay-2000 {
  animation-delay: 2s;
}

.animation-delay-4000 {
  animation-delay: 4s;
}
</style>
